import { Howl, Howler } from 'howler';



class Controller {
    instance;
    music_list;
    index;
    timer;
    loop;

    constructor(music_list) {
        this.music_list = music_list;
        this.index = 0;
        this.loop = false
        this.instance = new Howl({
            src: this.music_list[this.index],
            autoplay: false,
            loop: this.loop,
            volume: 0.5
        })
    }

    // 获取新Howl实例对象
    getNewHowl(src) {
        return new Howl({
            src: src,
            autoplay: false,
            loop: false,
            volume: 0.1
        })
    }

    // 播放
    play() {
        this.instance.play()
        return this.index;
    }

    // 暂停
    pause() {
        this.instance.pause()
    }

    // 停止
    stop() {
        this.instance.stop()
    }

    // 上一首
    pre() {
        if (this.index - 1 < 0) {
            this.index = this.music_list.length - 1
        } else {
            this.index--
        }
        if (this.instance != null) {
            this.pause()
        }
        this.instance = this.getNewHowl(this.music_list[this.index])
        return this.index;
    }

    // 下一首
    next() {
        if (this.index + 1 >= this.music_list.length) {
            this.index = 0
        } else {
            this.index++
        }
        if (this.instance != null) {
            this.pause()
        }
        this.instance = this.getNewHowl(this.music_list[this.index])
        return this.index;
    }

    // 改变音量
    setVolume(volume) {
        this.instance.volume(volume)
    }

    // 获取当前音量
    getVolume() {
        return this.instance.volume
    }

    // 静音
    mute() {
        this.instance.mute(true)
    }

    // 解除静音
    clearMute() {
        this.instance.mute(false)
    }

    // 获取总持续时间
    duration() {
        return this.instance.duration()
    }

    // 获取当前执行时间
    seek() {
        if (this.instance == null) {
            return 0
        } else {
            return this.instance.seek()
        }
    }

    // 获取当前播放进度
    scale() {
        return this.seek() / this.duration()
    }

    // 设置时间
    setSeek(seek) {
        this.instance.seek(seek);
    }

    // 设置为单曲循环
    isLoop(loop) {
        this.instance.loop(loop)
        this.loop = loop
        return this.loop
    }

}


export default Controller